package com.aidong.device.controllers;

import java.util.ArrayList;
import java.util.HashMap;

import com.aidong.device.util.ExUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aidong.device.controllers.concerns.Success;
import com.aidong.device.entity.ExLog;
import com.aidong.device.service.ExCodeService;

import java.util.Map;
import java.util.List;
import java.util.stream.Stream;

@RequestMapping("/nutrition/")
@RestController
public class ExchangeCodeController {
    @Autowired
    ExCodeService exCodeService;

    @RequestMapping(value = "{code}", method = RequestMethod.GET)
    public Success check(@PathVariable("code") String code,
                         @RequestParam("machineId") String machineId) {
        List<Integer> skuList = exCodeService.getExGoodList(machineId, code);
        return new Success(new ModelMap("sku", skuList));
    }

    @RequestMapping(value = "{code}", method = RequestMethod.POST)
    public Success notify(@PathVariable("code") String code,
                          @RequestParam("machineId") String machineId,
                          @RequestParam("sku") String sku) {
        String[] skuAry = sku.split(",");
        Map<Integer, Integer> goodMap = new HashMap<>();
        Stream.of(skuAry).forEach(tmp -> {
                    int goodId = Integer.parseInt(tmp);
                    Integer amount = goodMap.get(goodId);
                    if (amount == null) {
                        goodMap.put(goodId, 1);
                    } else {
                        goodMap.put(goodId, amount + 1);
                    }
                }
        );
        List<ExLog> exchangeLogs = new ArrayList<>();
        goodMap.forEach((key, value) -> exchangeLogs.add(new ExLog(code, machineId, ExUtil.N_LOG, key, value)));
        exCodeService.addExLog(exchangeLogs);
        return new Success(new ModelMap());
    }
}